import { ToolsService } from '@src/service/tools/tools.service';
import { ObjectType } from './../../../types/obj-type';
import { Controller, Get, Post, Body, HttpCode, HttpStatus, Request, Response, HttpException } from '@nestjs/common';
import { ApiTags, ApiOkResponse, ApiOperation, ApiCreatedResponse } from '@nestjs/swagger';
import { UserRep, UserLoginDto } from '../system/user/dto/index';
import { UserService } from '@src/service/admin/user/user.service';
import { create } from 'svg-captcha';
import { LoggerService } from '@src/service/admin/logger/logger.service';

@ApiTags('api-login')
@Controller('user')
export class LoginController {
  constructor(
    private readonly userService: UserService,
    private readonly loggerService: LoggerService,
    private readonly toolsService: ToolsService,
  ) {
  }

  /**
   * @Description: 用户登录
   * @param {type}
   * @return:
   */
  @ApiOperation({
    summary: '用户登录',
    description: '用户名可以是手机号码、邮箱、用户名',
  })
  @ApiCreatedResponse({
    type: UserLoginDto,
    description: '用户登录DTO',
  })
  @ApiOkResponse({ type: UserRep })
  @Post('login')
  async login(@Body() userLoginDto: UserLoginDto, @Request() req): Promise<UserRep> {
    if (req.session.captcha != userLoginDto.captcha.trim()) {
      throw new HttpException('验证码输入有误', HttpStatus.BAD_REQUEST)
    }
    this.loggerService.logger(req);
    return this.userService.login(userLoginDto);
  }

  /**
   * @Description: 生成验证码
   * @return:
   */
  @ApiOperation({
    summary: '生成验证码',
    description: '五位数验证码',
  })
  @Get('captcha')
  async getCaptchaCode(@Request() req): Promise<string> {
    const captcha = this.toolsService.getCaptcha();
    req.session.captcha = captcha.text.toLowerCase(); //存session用于验证接口获取文字
    return captcha.data;
  }

  /**
  * @Description: 生成验证码
  * @return:
  */
  @ApiOperation({
    summary: '退出登录',
    description: '清空校验信息',
  })
  @Get('loginout')
  async loginout(@Request() req): Promise<string> {
    req.session.captcha = null;
    return '退出成功';
  }
}
